package org.example.java.util.concurrency.atomic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * Created by juntaozhang on 3/15/15.
 */
public class AtomicIntegerFieldUpdaterDemo {
  static class Container {
    public volatile int number;
  }

  static class Task extends Thread {
    private AtomicIntegerFieldUpdater<Container> updater = AtomicIntegerFieldUpdater.newUpdater(Container.class, "number");
    private Container c;

    public Task(Container c) {
      this.c = c;
    }

    @Override
    public void run() {
      System.out.println(updater.addAndGet(c, 1));
      Thread.yield();
      System.out.println(updater.getAndIncrement(c));
    }
  }

  public static void main(String[] args) {
    Container c = new Container();
    ExecutorService exec = Executors.newCachedThreadPool();
    for (int i = 0; i < 100; i++)
      exec.execute(new Task(c));
    try {
      TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    exec.shutdown();
    System.out.println("================");
    System.out.println(c.number);
  }
}
